define([
	"static/app/tips",
	"UtilDir/util",
	"UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
	"Date","DateCN", "css!DateCss",
	"EasyUI","EasyUI-lang"
    ],function(tips, Util, Tool, SelectOrg, SearchBlock){

    var sysPath =  getServer() + "/static/app/zdyh/yhbridgeAssessment";

    var yhDisasterFormHtml = sysPath + "/views/yhDisasterForm.html";
	var getYhDisasterController = function(){
		return getServer() + "/yh/yhDisasters";
	};

	/**
	 * 页面初始化
	 */
	var init = function(){
        initSearchBlock();
        queryBtnBind();
        initcreateProvince();
//		initProviceSelect();
//		initCitySelect();
//		initAreaSelect();
		initYhEarthFortificationSelect();
		initYhFieldTypeSelect();
		initYhLotTypeSelect();
		// initReviewStatusSelect();
		//createYhDisasterGrid();
		initEvaluationResultSelect();
	};
    var initcreateProvince = function () {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer()+"/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    }
    var initcreateProvinceForm = function () {
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer()+"/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
	var initProviceSelect = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("proviceSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initCitySelect = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("citySelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initAreaSelect = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("areaSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhEarthFortificationSelect = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhEarthFortification",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhEarthFortificationSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhFieldTypeSelect = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhFieldType",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhFieldTypeSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhLotTypeSelect = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhLotType",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhLotTypeSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initReviewStatusSelect = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "reviewStatusSelect",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("reviewStatusSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initEvaluationResultSelect = function() {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "evaluationResultSelect",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("evaluationResultSelect");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	}

		var initProviceSelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("provice");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
		var initCitySelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("city");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
		var initAreaSelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("area");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhBuildingTimeSelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhBuildingTime");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhEarthFortificationSelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhEarthFortification",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhEarthFortification");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhEarthIntensitySelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhEarthIntensity",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhEarthIntensity");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
				$('#yhEarthIntensity').change(function(){
					var value = $(this).children('option:selected').val()
					if(value == '其他') {
						$('#otherEarthIntensityBox').show()
					} else {
						$('#otherEarthIntensityBox').hide()
					}
				})
			}
		});
	};
	var initYhNowEarthQhSelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhNowEarthQh",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhNowEarthQh");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhFieldTypeSelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhFieldType",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhFieldType");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhLotTypeSelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhLotType",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhLotType");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhExistingVirusSelectFrom = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "yhExistingVirus",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("yhExistingVirus");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
			}
		});
	};
	var initYhSeismicZoningForm = function () {
		$.ajax({
			url: getYhDisasterController() + "/getValidDictItemsByDictCode/" + "seismicZoning",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("seismicZoning");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i].dictItemName;
					var code = data[i].dictItemCode;
					mySelect.add(new Option(name, code));
				}
				$('#seismicZoning').change(function(){
					var value = $(this).children('option:selected').val()
					if(value == 1) {
						$('#surfaceAccelerationBox').show()
					} else {
						$('#surfaceAccelerationBox').hide()
						$('#surfaceAcceleration').val('')
					}
				})
			}
		});
	}

	var initSearchBlock = function(){
        SearchBlock.init("searchBlock");
	};
	var queryBtnBind = function(){
        $("#btnSearch").click(function () {
            createYhDisasterGrid();
        });
        $("#btnReset").click(function () {
			$("#yhCodeCondition").val("");
			$("#yhUnitCondition").val("");
			$("#yhProjectNameCondition").val("");
			$("#yhProjectTaskCondition").val("");
            $("#provinceSelect").val("");
            $("#citySelect").val("");
            $("#areaSelect").val("");
			$("#yhConstructionScaleCondition").val("");
            $("#yhEarthFortificationSelect").val("");
            $("#yhFieldTypeSelect").val("");
            $("#yhLotTypeSelect").val("");
            $("#evaluationResultSelect").val("");
		});
	};
	var createYhDisasterGrid= function() {
		var province = $("#provinceSelect").val();
		if(province==='' || province==null){
			Util.alert("请输入要操作的省份！");
			return;
		}
        $("#yhDisasterGrid").datagrid({
            url:getYhDisasterController() + "/queryYhDisasters/大型桥梁",
			method:"GET",
            fitColumns: true,
            autoRowHeight: false,
            columns:[[
                {field:"ck",checkbox:true},
				{
					field:'yhCode', sortable: true,
					title:'编号',
					width:'5%',
					align:'center',
				},
				{
					field:'yhUnit',
					title:'单位（小区）',
					width:'10%',
					align:'center',
					formatter:function(value,rowData,rowIndex){
						return '<a href="#" onclick="_editYhDisaster(\'' + rowData.id + '\',\'' + rowData.province + '\');"> '+rowData.yhUnit+' </a> '
					}
				},
				// {
				// 	field:'yhProjectName',
				// 	title:'建筑用途',
				// 	width:'8%',
				// 	align:'center',
				// 	formatter:function(value,rowData,rowIndex){
				// 		return '<a href="#" onclick="_editYhDisaster(\'' + rowData.id + '\');"> '+rowData.yhProjectName+' </a> '
				// 	}
				// },
				{
					field:'province', sortable: true,
					title:'省',
					width:'10%',
					align:'center',
				},
				{
					field:'city', sortable: true,
					title:'市',
					width:'10%',
					align:'center',
				},
				{
					field:'area', sortable: true,
					title:'区（县）',
					width:'10%',
					align:'center',
				},
				// {
				// 	field:'yhProjectTask',
				// 	title:'工程任务',
				// 	width:'8%',
				// 	align:'center',
				// },
				{
					field:'yhConstructionScale',
					title:'建设规模',
					width:'7%',
					align:'center',
				},
				{
					field:'yhEarthFortification',
					title:'抗震设防类别',
					width:'8%',
					align:'center',
					/*formatter: function (value) {
                        if (value == 0) {
                            return 'I类（甲类）';
                        } else if (value == 1) {
                            return 'II类（乙类）';
                        } else if (value == 2) {
                            return 'III类（丙类）';
                        } else if (value == 3) {
                            return 'IV类（丁类）';
                        }
                    }*/
				},
				{
					field:'yhFieldType',
					title:'场地类型',
					width:'10%',
					align:'center',
					/*formatter: function (value) {
                        if (value == 0) {
                            return 'Ⅰ类场地';
                        } else if (value == 1) {
                            return 'Ⅱ类场地';
                        } else if (value == 2) {
                            return 'Ⅲ类场地';
                        } else if (value == 3) {
                            return 'Ⅳ类场地';
                        }
                    }*/
				},
				// {
				// 	field:'yhLotType',
				// 	title:'地段类型',
				// 	width:'7%',
				// 	align:'center',
				// 	/*formatter: function (value) {
                //         if (value == 0) {
                //             return '有利';
                //         } else if (value == 1) {
                //             return '一般';
                //         } else if (value == 2) {
                //             return '不利';
                //         } else if (value == 3) {
                //             return '危险';
                //         }
                //     }*/
				// },
				{
					field: 'seismicZoning',
					title: '地震小区划',
					width: '10%',
					align: 'center',
					formatter: function (value) {
						if(value == 0) {
							return '无'
						} else if (value == 1) {
							return '有'
						}
					}
				},
				{
					field:'evaluationResult',
					title:'评估结果',
					width:'10%',
					align:'center',
					formatter: function (value) {
						var res = ''
                        if(value) {
							res = value
						} else {
							res = '未评估'
						}
						return res
                    }
				},
				{
					field:'deal',
					title:'操作',
					width:'10%',
					align:'center',
					formatter:function(value,rowData,rowIndex){
						return '<a href="#" onclick="_evaluate(\'' + rowData.id + '\',\'' + rowData.province + '\');">评估</a> '
					}
				},
            ]],
            toolbar: [{
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportForm();
                }
	         },{
                iconCls: 'fa fa-share-square-o',
                text: "批量评估（勾选）",
                handler: function () {
                    _evaluate();
                },
            },{
                iconCls: 'fa fa-download',
                text: "评估结果导出",
                handler: function () {
                    evaluateExportForm();
                }
	         }],
            queryParams:{
				yhCode: $("#yhCodeCondition").val(),
				yhUnit: $("#yhUnitCondition").val(),
				yhProjectName: $("#yhProjectNameCondition").val(),
				yhProjectTask: $("#yhProjectTaskCondition").val(),
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
				yhConstructionScale: $("#yhConstructionScaleCondition").val(),
                yhEarthFortification: $("#yhEarthFortificationSelect").val(),
                yhFieldType: $("#yhFieldTypeSelect").val(),
                yhLotType: $("#yhLotTypeSelect").val(),
				// reviewStatus: $("#reviewStatusSelect").val(),
				evaluationResult: $('#evaluationResultSelect').val()
            },
            pagination: true,
            pageSize: 10
        });
    };
	var formValidator = function(){
		$("#yhDisasterForm").validate({
			rules : {
				yhCode : {
					required : true,
				},
				yhUnit : {
					required : true,
				},
				// yhProjectName : {
				// 	required : true,
				// },
				// longitude : {
				// 	required : true,
				// 	number: true,
				// 	range:[-180,180]
				// },
				// latitude : {
				// 	required : true,
				// 	number: true,
				// 	range:[-90,90]
				// },
				provice : {
					required : true,
				},
				city : {
					required : true,
				},
				area : {
					required : true,
				},
				detailedAddress : {
					required : true,
				},
				yhProjectTask : {
					required : true,
				},
				yhConstructionScale : {
					required : true,
				},
				// yhConstructionPrice : {
				// 	required : true,
				// 	number: true
				// },
				yhBuildingTime : {
					required : true,
					yhBuildingTimeReg: true 
				},
				yhEarthFortification : {
					required : true,
				},
				yhEarthIntensity : {
					required : true,
				},
				otherEarthIntensity: {
					required : true,
				},
				yhNowEarthQh : {
					required : true,
				},
				yhFieldType : {
					required : true,
				},
				// yhLotType : {
				// 	required : true,
				// },
				yhExistingVirus : {
					required : true,
				},
				fillPerson : {
					required : true,
				},
				fillPersonTel : {
					required : true,
					isPhone: true
				},
				checkPerson : {
					required : true,
				},
				checkPersonTel : {
					required : true,
					isPhone: true
				},
				imageUrl : {
					required : true,
				},
			},
			messages : {
				yhCode : {
					required : "编号不允许为空!",
				},
				yhUnit : {
					required : "单位（小区）不允许为空!",
				},
				yhProjectName : {
					required : "建筑用途不允许为空!",
				},
				// longitude : {
				// 	required : "经度不允许为空!",
				// 	number: '请输入数字'
				// },
				// latitude : {
				// 	required : "纬度不允许为空!",
				// 	number: '请输入数字'
				// },
				provice : {
					required : "省不允许为空!",
				},
				city : {
					required : "市不允许为空!",
				},
				area : {
					required : "区（县）不允许为空!",
				},
				detailedAddress : {
					required : "详细地址不允许为空!",
				},
				yhProjectTask : {
					required : "工程任务不允许为空!",
				},
				yhConstructionScale : {
					required : "建设规模不允许为空!",
				},
				// yhConstructionPrice : {
				// 	required : "造价不允许为空!",
				// 	number: '请输入数字，单位万元'
				// },
				yhBuildingTime : {
					required : "建造年代不允许为空!",
				},
				yhEarthFortification : {
					required : "抗震设防类别不允许为空!",
				},
				yhEarthIntensity : {
					required : "原抗震设防烈度不允许为空!",
				},
				otherEarthIntensity : {
					required : "原抗震设防烈度不允许为空!",
				},
				yhNowEarthQh : {
					required : "现抗震设防烈度不允许为空!",
				},
				yhFieldType : {
					required : "场地类型不允许为空!",
				},
				yhLotType : {
					required : "地段类型不允许为空!",
				},
				yhExistingVirus : {
					required : "现存病害不允许为空!",
				},
				fillPerson : {
					required : "填表人不允许为空!",
				},
				fillPersonTel : {
					required : "填表人联系电话不允许为空!",
					isPhone: '请输入正确的手机号'
				},
				checkPerson : {
					required : "校核人不允许为空!",
				},
				checkPersonTel : {
					required : "校核人联系电话不允许为空!",
					isPhone: '请输入正确的手机号'
				},
				imageUrl : {
					required : "图片地址不允许为空!",
				},
			}
		});
		$.validator.addMethod('yhBuildingTimeReg',function(value,element,params){
			var reg = /^\d{4}$|^\d{4}年$|不清楚/
			return reg.test(value) 
		},'校验建造年代');
		$.validator.addMethod("isPhone", function(value, element) {
			var length = value.length;
			var mobile = /^1(3|4|5|6|7|8|9)\d{9}$/;
			return this.optional(element) || (length == 11 && mobile.test(value));
		   }, "请填写正确的手机号码");
	}
	var getYhDisaster = function(id,province){
		$.ajax({
			url: getYhDisasterController() + "/"+id+ "/"+province,
			type: "get",
			success: function (data) {
				editProvince(data.province, data.city, data.area);
				viewFileUpload(data.imageUrl, 'multiFileUpload', 'imageUrl');
				viewFileUpload(data.typicalHazardPhotos, 'multiFileUploadTypicalHazardPhotos', 'typicalHazardPhotos');

				if(data.yhEarthIntensity == '其他'){
					$('#otherEarthIntensityBox').show()
				}
				if(data.seismicZoning == '1') {
					$('#surfaceAccelerationBox').show()
				}
				Tool.deserialize("yhDisasterForm", data);
				formDisabled()
			}
		});
	};
	// var getYhDisaster = function(id){
	// 	$.ajax({
	// 		url: getYhDisasterController() + "/"+id,
	// 		type: "get",
	// 		success: function (data) {
	// 			editProvince(data.province, data.city, data.area);
    //             viewFileUpload(data.imageUrl, 'multiFileUpload', 'imageUrl');
    //             viewFileUpload(data.typicalHazardPhotos, 'multiFileUploadTypicalHazardPhotos', 'typicalHazardPhotos');
	//
    //             if(data.yhEarthIntensity == '其他'){
	// 				$('#otherEarthIntensityBox').show()
	// 			}
	// 			if(data.seismicZoning == '1') {
	// 				$('#surfaceAccelerationBox').show()
	// 			}
	// 			Tool.deserialize("yhDisasterForm", data);
	// 			formDisabled()
	// 		}
	// 	});
	// };
    var editProvince = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer()+"/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer()+"/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
	var addYhDisaster = function () {
		var slidebar = Util.slidebar({
			url: yhDisasterFormHtml,
			width: "800px",
			cache: false,
			close : true,
			afterLoad: function () {
				initcreateProvinceForm();
				fileUpload();
//				initProviceSelectFrom();
//				initCitySelectFrom();
//				initAreaSelectFrom();
//				initYhBuildingTimeSelectFrom();
				initYhEarthFortificationSelectFrom();
				initYhEarthIntensitySelectFrom();
				initYhNowEarthQhSelectFrom();
				initYhFieldTypeSelectFrom();
				initYhLotTypeSelectFrom();
					initYhExistingVirusSelectFrom();
				initYhSeismicZoningForm();
				formValidator();
				tips.gettips();
				$("#saveBtn").on("click", function () {
					if($("#yhDisasterForm").valid()){
						var data = Tool.serialize("yhDisasterForm");
						$.ajax({
							url: getYhDisasterController()+"/大型桥梁" ,
                            contentType:"application/json",
							data: JSON.stringify(data),
							type: "post",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
                                createYhDisasterGrid();
							}
						});
					}
				});
			}
		});
	};
	window._editYhDisaster = function(yhDisasterId,province) {
		var slidebar = Util.slidebar({
			url: yhDisasterFormHtml,
			width: "800px",
			cache: false,
			close : true,
			afterLoad: function () {
//				initProviceSelectFrom();
//				initCitySelectFrom();
//				initAreaSelectFrom();
//				initYhBuildingTimeSelectFrom();
				initYhEarthFortificationSelectFrom();
				initYhEarthIntensitySelectFrom();
				initYhNowEarthQhSelectFrom();
				initYhFieldTypeSelectFrom();
				initYhLotTypeSelectFrom();
				initYhExistingVirusSelectFrom();
				initYhSeismicZoningForm();
				formValidator();
				tips.gettips();
				getYhDisaster(yhDisasterId,province);
				$("#saveBtn").on("click", function () {
					if($("#yhDisasterForm").valid()){
						var data = Tool.serialize("yhDisasterForm");
						$.ajax({
							url: getYhDisasterController(),
							contentType:"application/json",
							data: JSON.stringify(data),
							type: "put",
							success: function (data) {
								Util.alert(data.message);
								slidebar.close();
								createYhDisasterGrid();
							}
						});
					}
				});
			}
		});
	};
// 	window._editYhDisaster = function(yhDisasterId) {
// 		var slidebar = Util.slidebar({
// 			url: yhDisasterFormHtml,
// 			width: "800px",
// 			cache: false,
// 			close : true,
// 			afterLoad: function () {
// //				initProviceSelectFrom();
// //				initCitySelectFrom();
// //				initAreaSelectFrom();
// //				initYhBuildingTimeSelectFrom();
// 				initYhEarthFortificationSelectFrom();
// 				initYhEarthIntensitySelectFrom();
// 				initYhNowEarthQhSelectFrom();
// 				initYhFieldTypeSelectFrom();
// 				initYhLotTypeSelectFrom();
// 					initYhExistingVirusSelectFrom();
// 				initYhSeismicZoningForm();
// 				formValidator();
// 				tips.gettips();
// 				getYhDisaster(yhDisasterId);
// 				$("#saveBtn").on("click", function () {
// 					if($("#yhDisasterForm").valid()){
// 						var data = Tool.serialize("yhDisasterForm");
// 						$.ajax({
// 							url: getYhDisasterController(),
//                             contentType:"application/json",
//                             data: JSON.stringify(data),
// 							type: "put",
// 							success: function (data) {
// 								Util.alert(data.message);
// 								slidebar.close();
// 								createYhDisasterGrid();
// 							}
// 						});
// 					}
// 				});
// 			}
// 		});
// 	};
	//
	var formDisabled = function() {
		$('#yhCode').attr("readOnly","true");
		$('#yhUnit').attr("readOnly","true");
		$('#yhProjectName').attr("readOnly","true");
		$('#longitude').attr("readOnly","true");
		$('#latitude').attr("readOnly","true");
		$('#province').attr("disabled","disabled");
		$('#city').attr("disabled","disabled");
		$('#area').attr("disabled","disabled");
		$('#detailedAddress').attr("readOnly","true");
		$('#yhProjectTask').attr("readOnly","true");
		$('#yhConstructionScale').attr("readOnly","true");
		$('#yhConstructionPrice').attr("readOnly","true");
		$('#yhBuildingTime').attr("readOnly","true");
		$('#yhEarthFortification').attr("disabled","disabled");
		$('#yhEarthIntensity').attr("disabled","disabled");
		$('#otherEarthIntensity').attr("readOnly","true");
		$('#yhNowEarthQh').attr("disabled","disabled");
		$('#yhFieldType').attr("disabled","disabled");
		$('#yhLotType').attr("disabled","disabled");
		$('#yhExistingVirus').attr("disabled","disabled");
			$('#fillPerson').attr("readOnly","true");
		$('#fillPersonTel').attr("readOnly","true");
	$('#seismicZoning').attr("readOnly","true");
		$('#surfaceAcceleration').attr("readOnly","true");		$('#checkPerson').attr("readOnly","true");
		$('#checkPersonTel').attr("readOnly","true");
	}
	// 评估
	window._evaluate = function(yhDisasterId,province) {
		var param = {};

		if(yhDisasterId) {
			param.province = province;
			console.log(yhDisasterId)
			param.yhDisasterId = yhDisasterId;
			$.ajax({
				url: getYhDisasterController() + "/evaluate",
				contentType: "application/json",
				data: JSON.stringify(param),
				type: "post",
				success: function (data) {
					createYhDisasterGrid();
				}
			});
		} else {
			if ($("#provinceSelect").val()=='' || $("#provinceSelect").val()==null){
				Util.alert('请选择省！');
				return;
			}
			param.province = $("#provinceSelect").val();
			var rows = $("#yhDisasterGrid").datagrid("getSelections");
			if (rows == null || rows.length == 0) {
				Util.alert("请选择一行数据!");
				return;
			}
			var ids = "";
			$.each(rows, function (i, row) {
				ids += row.id + ",";
			});
			ids = ids.substr(0, ids.length - 1);
			param.yhDisasterId = ids;
			console.log(ids)
			$.ajax({
				url: getYhDisasterController() + "/evaluate",
				contentType: "application/json",
				data: JSON.stringify(param),
				type: "post",
				success: function (data) {
					createYhDisasterGrid();
				}
			});
		}
	}
	var deleteYhDisaster = function() {
		var province = $("#provinceSelect").val();
		if(province==='' || province==null){
			Util.alert("请输入要操作的省份！");
			return;
		}
		var rows = $("#yhDisasterGrid").datagrid("getSelections");
		if (rows == null || rows.length == 0) {
			Util.alert("请选择一行数据!");
			return;
		}
		Util.confirm("是否要删除选中的数据?", function() {
			var ids = "";
			$.each(rows, function(i, row){
				ids += (row.id + "_" + row.province + ",");

			});
			ids = ids.substr(0,ids.length - 1);
			$.ajax({
				url: getYhDisasterController() ,
				data: {
					ids : ids
				},
				type: "delete",
				success: function (data) {
					createYhDisasterGrid();
				}
			});
		}, function() {
			return;
		});

	};
	//导入
    var importForm = function () {

        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
          	var url = getServer() + "/excel/重点隐患.xls";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getYhDisasterController() + "/importDisaster",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
					createYhDisasterGrid();
                }
            });
        });
    };
    //导出
    var exportForm = function () {
		var yhCode=$("#yhCodeCondition").val();
		var	yhUnit=$("#yhUnitCondition").val();
		var yhProjectName= $("#yhProjectNameCondition").val();
		var	yhProjectTask= $("#yhProjectTaskCondition").val();
		var province= $("#provinceSelect").val();
		var	city=$("#citySelect").val();
		var area=$("#areaSelect").val();
		var yhConstructionScale=$("#yhConstructionScaleCondition").val();
		var yhEarthFortification= $("#yhEarthFortificationSelect").val();
		var yhFieldType=$("#yhFieldTypeSelect").val();
		var yhLotType=$("#yhLotTypeSelect").val();
		// var reviewStatus=$("#reviewStatusSelect").val();
		var evaluationResult = $('#evaluationResultSelect').val();
		if(province==='' || province==null){
			Util.alert("请输入要操作的省份！");
			return;
		}
		window.location.href = getYhDisasterController() + "/exportFile/大型桥梁?yhCode="+yhCode+"&yhUnit="+yhUnit+"&yhProjectName"+yhProjectName+"&yhProjectTask="+yhProjectTask+"&province="+province+"&city="+city+"&area="+area+"&yhConstructionScale="+yhConstructionScale+"&yhEarthFortification="+yhEarthFortification+"&yhFieldType="+yhFieldType+"&yhLotType="+yhLotType+"&evaluationResult="+evaluationResult;
    };
    //提交
    var submit = function () {
		if($("#provinceSelect").val()==='' || $("#provinceSelect").val()==null){
			Util.alert("请输入要操作的省份！");
			return;
		}
        var rows = $("#yhDisasterGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        if (rows.length >= 1) {
            for (var i = 0; i < rows.length; i++) {
                if (rows[i].reviewStatus != '0') {
                    Util.alert("只有数据状态为未提交的才能提交!");
                    return;
                }
            }
        }
        Util.confirm("是否要提交选中的表单?", function () {
            var ids = "";
			$.each(rows, function(i, row){
				ids += (row.id + "_" + row.province + ",");

			});
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getYhDisasterController() + "/submit",
                contentType: "application/json",
                data: JSON.stringify(rows),
                type: "post",
                success: function (data) {
					createYhDisasterGrid();
                }
            });
        }, function () {
            return;
        });

    };
	var FILE_TYPES = {
		image: {
			title: '图片文件',
			extensions: 'jpg,jpeg,bmp,png,ico',
			mimeTypes: 'image/bmp,image/jpeg,image/png,image/x-icon'
		},
		doc: {
			title: '文档文件',
			extensions: 'doc,docx,xls,xlsx,ppt,pptx,pdf',
			mimeTypes: 'application/vnd.ms-excel.12,application/vnd.ms-word.document.12,application/vnd.ms-powerpoint.12,' +
				'application/pdf,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword'
		},
		video: {
			title: '视频文件',
			extensions: 'mp4,avi,mov,mpg',
			mimeTypes: 'video/mpeg,video/quicktime,video/x-msvideo,'
				+ 'application/vnd.rn-realmedia-vbr,video/mp4'
		},
		audio: {
			title: '音频文件',
			extensions: 'wma,mp3,wav',
			mimeTypes: 'audio/x-ms-wma,audio/mpeg,audio/x-wav'
		},
		packet: {
			titil: '压缩包',
			extensions: 'zip,rar',
			mimeTypes: 'application/zip,application/x-rar-compressed'
		}
	};
	var fileUpload = function () {
		require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
			var attachId = "";
			var settings = {
				placeAt: "multiFileUpload",
				accept: FILE_TYPES.image,
				/*
                1.0.2版本新增
                extendColumn:[
                    {name:"文件分类",filed:"category",format:function(file){return file.name}},
                    {name:"备注",filed:"remark",format:function(file){return '机密'}}
                ],*/
				//data:["5a50d697c0af806aa01e06120d04f977","6c01e4492f264befab4c0532811f8dff"],
				onUploadSuccess: function (file) {
					attachId += file.attachId + ",";
					$("#imageUrl").val(attachId.substr(0, attachId.length - 1));
				},
				onDeleteSavedFile: function (file) {
					//console.log(file)
				}
			};
			var MFUpload = MFU.init(settings);

		});
	};
var viewFileUpload = function (fileData, palceAt,id) {
        require(['UtilDir/fileupload/multiFileUpload'], function (MFU) {
            var attachIdData = "";
            var attachId = "";
            var fileArray = fileData && fileData.split(',') || [];
            if (fileData && fileData.length != 0) {
                attachIdData = fileData.split(',');
            }
            var settings = {
                placeAt: palceAt,
				accept: FILE_TYPES.image,
                /*
	            1.0.2版本新增
	            extendColumn:[
	                {name:"文件分类",filed:"category",format:function(file){return file.name}},
	                {name:"备注",filed:"remark",format:function(file){return '机密'}}
	            ],*/
                data: attachIdData,
                onUploadSuccess: function (file) {
					console.log(file);
                    attachId += file.attachId + ",";
                    if (fileData && fileData.length == 0) {
                        $("#"+ id).val(attachId.substr(0, attachId.length - 1));
                    } else {
                        $("#"+ id).val(fileData + "," + attachId.substr(0, attachId.length - 1));
                    }

                },
                onDeleteSavedFile: function (file) {
                    var index = fileArray.indexOf(file.attachId);
                    fileArray.splice(index, 1);
                    $("#"+ id).val(fileArray.toString());
                }
            };
            var MFUpload = MFU.init(settings);

        });
    };	return {
		init:init
	};
});
